package com.gitee.neuray.security.gateway.strategy;

import com.gitee.neuray.security.admin.authority.PermissionElementDto;
import com.gitee.neuray.security.common.exception.BaseException;
import com.netflix.zuul.context.RequestContext;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: zhhongyu
 * @description: 校验按钮权限
 * @since: Create in 9:42 2020/3/27
 */
public class ButtonPermission extends AbstratePermissionStrategy {
    /**
     * 校验到按钮级别
     *
     * @param permissionInfos
     * @param ctx
     */
    @Override
    public PermissionElementDto checkout(List<PermissionElementDto> permissionInfos, RequestContext ctx) {
        String requestUri = getRequestUri(ctx);
        if (StringUtils.isEmpty(requestUri)) {
            throw new BaseException("请求的requesturi error... ");
        }
        checkargs(permissionInfos);
        //开始校验权限
        permissionInfos = permissionInfos.stream()
                .filter(permissionInfo -> {
                    if (StringUtils.isEmpty(permissionInfo.getUri())) {
                        return false;
                    }
                    return requestUri.contains(permissionInfo.getUri());
                }).collect(Collectors.toList());
        if (permissionInfos.size() == 0) {
            sendZuulResponseError40301();
            return null;
        }
        boolean anyMatch =
                permissionInfos.parallelStream()
                        .anyMatch(permissionInfo -> ctx.getRequest().getMethod().equals(permissionInfo.getMethod()));
        if (anyMatch) {
            //该用户有访问路径权限
            //实现一个策略取出来路径匹配度最高的，为确定权限
            PermissionElementDto max = Collections.max(permissionInfos);
            return max;
        } else {
            sendZuulResponseError40305();
        }
        return null;
}
}
